package server;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

public class WebClassLoader extends ClassLoader {


    /**
     * @param className class文件全限定类名 server.HelloServlet
     * @param basePath  class文件的根目录 D:\MyProject\Minicat\webapps\demo1\
     * @return
     * @throws ClassNotFoundException
     */
    protected Class<?> findClass(String className, String basePath) throws ClassNotFoundException {
        byte[] classByte = null;
        String path = basePath + File.separatorChar + className.replace(".", "\\") + ".class";
        FileInputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        System.out.println("path：" + path);
        try {
            inputStream = new FileInputStream(path);
            outputStream = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            classByte = outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Class<?> aClass = findLoadedClass(className);
        if (aClass != null) {
            return aClass;
        }
        return defineClass(className, classByte, 0, classByte.length);
    }

    public static void main(String[] args) {
        WebClassLoader webClassLoader = new WebClassLoader();
        Class<?> aClass = null;
        try {
            aClass = webClassLoader.loadClass("server.HttpServlet");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}
